/*
 * @Author: zhangfeng
 * @Date: 2023-11-30 18:08:21
 * @LastEditTime: 2024-01-18 18:06:27
 * @LastEditors: zhangfeng
 * @Description:
 * @FilePath: \manager\managersystem\src\utils\request.ts
 * © 2023 张峰，All rights reserved.
 */
import axios, { AxiosResponse } from 'axios';
import router from '../router/index';
import { user } from '../store/index';

const baseConfig = {
	baseURL: import.meta.env.VITE_API_PREFIX,
	timeout: 3000,
	headers: {
		'content-type': 'application/json;charset=utf-8',
	},
};
const request = axios.create(baseConfig);

/**
 * @description: 请求拦截
 * @param {参数} config
 * @return {返回值}
 */
request.interceptors.request.use((config) => {
	config.headers = config.headers || {};
	if (localStorage.getItem('saveToken')) {
		config.headers.Authorization = localStorage.getItem('saveToken') || '';
	}
	return config;
});
/**
 * @description: 响应拦截
 * @return {返回值}
 */
request.interceptors.response.use(
	(res: AxiosResponse<any>): Promise<AxiosResponse<ResponseData, any>> => {
		const status: number = res.status;
		const code: number | string = res.data.code;
		if (status == 500) {
			ElMessage({
				message: res.data.message,
				grouping: true,
				type: 'error',
			});
			return Promise.reject(res.data);
		} else if (status == 200) {
			if (code == 10101 || code == 10102 || code == 10103) {
				ElMessageBox({
					title: res.data?.message,
					message: h('p', null, [h('span', null, ' 请重新登录 ')]),
					showCancelButton: false,
					confirmButtonText: '确定',
					showClose: false,
					closeOnClickModal: false,
					beforeClose: (action, instance, done) => {
						if (action === 'confirm') {
							instance.confirmButtonLoading = true;
							instance.confirmButtonText = 'Loading...';
							done();
						} else {
							done();
						}
					},
				})
					.then((action) => {
						const token = user();
						token.removeToken();
						router.push('/login');
					})
					.catch(() => {});
				return Promise.reject();
			} else if (code !== 0) {
				ElMessage({
					message: res.data.message,
					grouping: true,
					type: 'error',
				});
				return Promise.reject(res.data);
			} else {
				return Promise.resolve(res.data);
			}
		} else {
			return Promise.reject(res.data);
		}
	},
	(err: AxiosError<ResponseData>): Promise<AxiosResponse<ResponseData, any>> => {
		ElMessage({
			message: err.message,
			grouping: true,
			type: 'error',
		});
		console.error(err);
		return Promise.reject(err);
	}
);

export default request;
